package by.ostrovsky.webhousingsystem.controller.account;

import org.apache.log4j.Logger;

import by.ostrovsky.webhousingsystem.constants.Constants;
import by.ostrovsky.webhousingsystem.controller.IUserController;
import by.ostrovsky.webhousingsystem.dao.DAOFactory;
import by.ostrovsky.webhousingsystem.dao.implementation.idao.IReadDAO;
import by.ostrovsky.webhousingsystem.exception.AccessDeniedException;
import by.ostrovsky.webhousingsystem.exception.CommonException;
import by.ostrovsky.webhousingsystem.exception.OperationErrorException;
import by.ostrovsky.webhousingsystem.hibernate.entity.Account;

public class LoginController implements IUserController<Account, Boolean>{
	private static Logger logger = Logger.getLogger(LoginController.class);

	@Override
	public String login(Account account) throws OperationErrorException,
			AccessDeniedException {
		try {
			DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.MySQL);
			IReadDAO<Account> dao = factory.getReadAccountDAO();	
			
			Account acc = dao.read(account);
			
			Boolean match = acc.getId().equals(account.getId());
			match = match && acc.getHashed().equals(account.getHashed());
			if (match)
				return Constants.getAccessLevelByKey(acc.getAccessLevel());
		}catch(NullPointerException e){			
			throw new AccessDeniedException();
		} 
		catch (Exception e) {
			logger.fatal(e);
			throw new OperationErrorException();
		}
		throw new OperationErrorException();
	}

	@Override
	public Boolean send(Account object) throws CommonException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Boolean registrate(Account object) throws CommonException {
		// TODO Auto-generated method stub
		return null;
	}
}
